from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    Name = serializers.CharField()
    Tel = serializers.CharField(required=False, allow_blank=True)
    Mobile = serializers.CharField(required=False, allow_blank=True)
    ProvinceName = serializers.CharField()
    CityName = serializers.CharField()
    ExpAreaName = serializers.CharField()
    Address = serializers.CharField()
    PostCode = serializers.CharField(required=False, allow_blank=True)


    def validate(self, attrs):
        if not(attrs.get('Tel') or attrs.get('Mobile')):
            raise serializers.ValidationError('电话或者手机必须填写一个')
        return attrs


class CommoditySerializer(serializers.Serializer):
    GoodsName = serializers.CharField()


class PlaceOrderSerializer(serializers.Serializer):
    # Commodity = "鞋子;袜子"

    # Commodity = [
    #   {"GoodsName": “鞋子”}
    #   {""GoodsName": "袜子"}
    # ]

    Commodity = CommoditySerializer(many=True)
    Receiver = UserSerializer()
    Sender = UserSerializer()
    OrderCode = serializers.CharField()
    ShipperCode = serializers.CharField()
    PayType = serializers.IntegerField()
    ExpType = serializers.IntegerField()
    Quantity = serializers.IntegerField()

    def validate(self, attrs):
        if attrs['ShipperCode'] in ['EMS', 'YZPY', 'YZBK']:
            p1 = attrs.get("Receiver").get("PostCode")
            p2 = attrs.get("Sender").get("PostCode")
            if not all([p1, p2]):
                raise serializers.ValidationError('所选物流必填邮编!')
        return attrs

# data = {"Commodity": "鞋子;袜子"}
# c = data['Commodity']
# data['Commodity'] = []
# for temp in c.split(";"):
#     data['Commodity'].append({
#         "GoodsName": temp
#     })
#
# p = PlaceOrderSerializer(data=data)


